#include<stdio.h>
#include<stdlib.h>

/*
 * Note: The returned array must be malloced, assume caller calls free().
 */
struct node {
    int value;
    int index;
};

static int qcmp(const void *a, const void *b) {
    // printf("%d\t%d\n", *(int *)a, *(int *)b);
    // *(int *)a 将a强制声明为指向整数的指针，然后读取该指针所指的整数
    // ((struct node *)a) 将a强制声明为指向node结构体的指针，然后读取其中的value值
    return ((struct node *) a)->value - ((struct node *) b)->value;
}

int *twoSum(int *nums, int numsSize, int target) {
    int *indices = NULL;
    struct node *nodes = NULL;
    int i, j;
    int sum;
    int k;

    indices = (int *) malloc(sizeof(int) * 2);
    nodes = (struct node *) malloc(sizeof(struct node) * numsSize);
    k = numsSize;
    for (i = 0; i < numsSize; i++) {
        nodes[i].value = nums[i];
        nodes[i].index = i + 1;
    }

    qsort(nodes, numsSize, sizeof(struct node), qcmp);

    for (i = 0; i < k; i++) {
        for (j = i + 1; j < k; j++) {
            sum = nodes[i].value + nodes[j].value;
            if (target < sum) {
                k = j;
            } else if (target == sum) {
                if (nodes[i].index > nodes[j].index) {
                    indices[0] = nodes[j].index;
                    indices[1] = nodes[i].index;
                    //printf("%d\t%d\n", indices[0], indices[1]);
                    //printf("%x\t%x\n", &indices[0], &indices[1]);
                } else {
                    indices[0] = nodes[i].index;
                    indices[1] = nodes[j].index;
                    //printf("%d\t%d\n", indices[0], indices[1]);
                    //printf("%x\t%x\n", &indices[0], &indices[1]);
                }
                return indices;
            }
        }
    }
    return 0;
}

int main()
{
    int nums[] = {1, 51 , 35, 2, 7, 13};
    int target = 9;
    int *indices = NULL;
    indices = (int *)malloc(sizeof(int) * 2);
    indices = twoSum(nums, 6, target);
    printf("index1=%d, index2=%d\n", *indices, *(indices+1));
    printf("%d\t%d\n", indices[0], indices[1]);
    //这种输出写法是错误的
    //printf("%d\t%d\n", *indices, *indices++);

    //qsort(nums, 6, sizeof(nums[0]), qcmp);
    //int i;
    //for (i = 0; i < 6; i++) {
    //    printf("%d\n", nums[i]);
    //}

    return 0;
}
